﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace wd_31_test_other_interface_v1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public static string FAILED_AUTHENTICATE = "failed to authenticate";
        private async Task<string> AdbConnectServer(string ip, int port)
        {
            return await Task<string>.Run(() =>
            {
                string err_msg = string.Empty;
                int count_err = 0;
                while (count_err < 5)
                {
                    Process p = new Process();

                    string ip_port = string.Format("{0}:{1}", ip, port);

                    p.StartInfo.FileName = "adb.exe";
                    p.StartInfo.Arguments = "connect " + ip_port;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.RedirectStandardInput = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError = true;
                    p.StartInfo.CreateNoWindow = true;

                    //p.Start();

                    //string unicodeString = p.StandardOutput.ReadToEnd();    //获取错误信息
                    //byte[] buffer = Encoding.GetEncoding("GB2312").GetBytes(unicodeString);
                    //err_msg = Encoding.UTF8.GetString(buffer);   //修正中文乱码
                                                                 //ShowStatusBar(content);
                    Thread.Sleep(1);
                    //p.Close();

                    err_msg = FAILED_AUTHENTICATE;  //1
                    err_msg = "failed to authenticate";  //2
                    if (0 <= err_msg.IndexOf(FAILED_AUTHENTICATE))
                    {
                        Thread.Sleep(1000);
                        Trace.WriteLine(string.Format("loop time {0}", count_err));
                        count_err++;
                        continue;
                    }
                    break;
                }
                Trace.WriteLine(string.Format("loop over"));
                return err_msg;
            });
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            await AdbConnectServer("123", 124);
        }
    }
}
